//
//  EmotionKeyBoardView.swift
//  EmotionKeyboard
//
//  Created by 史亚洲 on 16/1/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//注意:闭包不会立即执行,需要等待用户输入,才能够执行
//不需要导入命名空间


private let EmotionCellId="EmotionCellId"
private let emotionCellMargin: CGFloat=5
private let rowCount: CGFloat=7
private let toolBarHeight: CGFloat=35

class EmotionKeyBoardView: UIView {
    
    
    //MARK:定义外部变量
    private lazy var packages=EmotionManager().packages
    
    var selectEmotion: ((em: Emotion)->())?

    @objc private func itemDidClick(item: UIBarButtonItem) {
        print(__FUNCTION__)
        print(item.tag)
        
        //滚动集合视图
        let indexPath=NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
     
    
    }
    
    //找到自定义入口
    init(selectEmotion: (em: Emotion)->()){
        self.selectEmotion=selectEmotion
        //指定键盘的高度,键盘默认高度为216;iPhone 6+/6s系统键盘高度为226
        let rect = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 220)
        super.init(frame: rect)
        setupUI()
           }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI界面
    private func setupUI() {
        
        addSubview(collectionView)
        addSubview(toolBar)
        
        //设置约束,注意:///底部相对于toolbar  不能够在这个时候添加底部约束 因为tool还没有添加约束
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.right.left.equalTo(self)
        }
        
        
        //设置toolBar
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            
            make.height.equalTo(toolBarHeight)
            make.top.equalTo(collectionView.snp_bottom)
        }
        
        //设置控件
        setToolbar()
        
    }
    //MARK:懒加载子视图
    //1.layout
    private lazy var collectionView: UICollectionView = {
        
        //1.1获取对象
       let layout=UICollectionViewFlowLayout()
        
        //1.2设置layout
        //滚动方向
        layout.scrollDirection = .Horizontal
        
        //itemSize
        let w=UIScreen.mainScreen().bounds.width/rowCount
        layout.itemSize=CGSize(width: w, height: w)
        
        //间距
        layout.minimumLineSpacing=0
        layout.minimumInteritemSpacing=0
        
        //平均垂直方向上的间距
        let padding=(self.bounds.height-toolBarHeight-3*w)/4
        
        //设置组与组之间的间距
        layout.sectionInset=UIEdgeInsets(top: padding, left: 0, bottom: padding, right: 0)

        //1.3设置collectionView
        let CV=UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        //2.注册cell
        CV.registerClass(EmotionCell.self, forCellWithReuseIdentifier: EmotionCellId)
        
        //3.设置数据源代理
        CV.dataSource=self
        CV.delegate=self
        
        //4.设置分页效果
        CV.pagingEnabled=true
        
        //5.设置背景颜色
        CV.backgroundColor=UIColor.whiteColor()
        
        return CV
        
    }()
    
    //2.工具条toolBar
    private lazy var toolBar: UIToolbar=UIToolbar()
}
//MARK:实现数据源方法
extension EmotionKeyBoardView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //在iOS上一般交互的控件原则上不能大小40
        return packages[section].emotions.count
     }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmotionCellId, forIndexPath: indexPath) as! EmotionCell
        
//        cell.backgroundColor=indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.brownColor()
        //cell.str="\(indexPath.section)+\(indexPath.item)"
        cell.emotion = packages[indexPath.section].emotions[indexPath.item]
        return cell
    }
    
    //MARK:点击cell的协议方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let em=packages[indexPath.section].emotions[indexPath.item]
        //1.没有智能提示 这个就不要等智能提示 给自己加上可选项的 '?'
        //2. 加 '.'
        //3: 删 '.'
       selectEmotion?(em: em)
    }
    
}
//MARK:==============自定义cell==================
class EmotionCell: UICollectionViewCell {
    
    var emotion: Emotion? {
        
        didSet {
            //emtionBtn.setTitle(emotion?.chs ?? "" , forState: .Normal)
            
            //bundle路径下的图片要使用绝对路径,不能这样设置图片
            
            print(emotion?.imagePath)
            emtionBtn.setImage(UIImage(contentsOfFile: emotion?.imagePath ?? ""), forState: .Normal)
        
            emtionBtn.setTitle(emotion?.emojiStr ?? "", forState: .Normal)
            if  let em=emotion where em.isDelete {
                //设置删除按钮
                //设置删除按钮
                emtionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }

        
        }
        
    }
    
  
    
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI界面
    private func setupUI() {
        
        //1.设置按钮的不可交互
        emtionBtn.userInteractionEnabled=false
        
        //2.添加
        contentView.addSubview(emtionBtn)
        
        //3.设置字体大小
        emtionBtn.titleLabel?.font=UIFont.systemFontOfSize(32)
        
        //4.设置约束
        emtionBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        
    }
    //MARK:懒加载子视图
    private lazy var emtionBtn: UIButton = UIButton()
    
    
    
}




//设置底部toolBar
extension EmotionKeyBoardView {
    
    private func setToolbar() {
        
        //设置字体颜色
        toolBar.tintColor=UIColor.darkGrayColor()
        
        var items=[UIBarButtonItem]()
        
     
        //定义索引
        var index=0
        //向数组中添加item
        for p in packages {
            
            //添加弹簧
            let space1=UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(space1)
            let item = UIBarButtonItem(title: p.group_name_cn, style:
                .Plain, target: self, action: "itemDidClick:")
            
            //添加到数组中
            items.append(item)
            
            item.tag = index++
            
            //添加弹簧
            let space2=UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
        
            items.append(space2)
       
        }
        toolBar.items=items
    }
}